﻿using BCCommon;
using BCCommon.Enums;
using BCCommon.PaymentEnums;
using BCCommon.TMS.RedPacket;
using BCData.Common.FlowRecord;
using BCData.Common.IP;
using BCData.Common.Wallet;
using BCData.TMS.Agent.AgentRecord;
using BCData.TMS.RedPacket.RedPacket;
using BCData.TMS.RedPacket.RedPacketReceive;
using BCData.Website.User.User;
using BCData.Website.User.UserAuth;
using BCData.WeChatComponent.WeChatUserInfo;
using BCDto.Common.IP;
using BCDto.Sim.Admin.Admin;
using BCDto.TMS.RedPacket.RedPacket;
using BCDto.Website.User;
using BCDto.WeChatComponent.WeChatUser;
using BCEntity.Common.EntityNameConst;
using BCEntity.Common.FlowRecord;
using BCEntity.Common.IP;
using BCEntity.TMS.RedPacket.RedPacketReceive;
using BCEntity.Website.User;
using BCService.Common.Area;
using BCService.Common.RedisClear;
using BCService.Common.Wallet;
using BCService.TMS.Agent.AgentAreaRecord;
using BCService.TMS.Agent.AgentRecord;
using BCService.Utils;
using BCService.WeChatComponent.WeChatUserRelevantService;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BCService.Website.User
{
    /// <summary>
    /// 用户信息服务
    /// </summary>
    public class UserService : IUserService
    {
        private readonly IApplicationContextService applicationContextService;
        private readonly IUserAuthData userAuthData;
        private readonly IUserData userData;
        private readonly IIPAddressRecordData ipAddressRecordData;
        private readonly IWeChatUserInfoData weChatUserInfoData;
        private readonly IWeChatUserRelevantService weChatUserRelevantService;
        private readonly IRedisService redisService;
        private readonly IRedisClearService redisClearService;
        private readonly IAgentAreaRecordService agentAreaRecordService;
        private readonly IRedPacketData redPacketData;
        private readonly IDatabaseContext databaseContext;
        private readonly IRedPacketReceiveData redPacketReceiveData;
        private readonly IWalletData walletData;
        private readonly IUserFlowRecordData userFlowRecordData;
        private readonly IWalletService walletService;
        private readonly IZoneService zoneService;
        public UserService(IApplicationContextService applicationContextService,
            IUserAuthData userAuthData,
            IUserData userData,
            IIPAddressRecordData ipAddressRecordData,
            IWeChatUserInfoData weChatUserInfoData,
            IWeChatUserRelevantService weChatUserRelevantService,
            IRedisService redisService,
            IRedisClearService redisClearService,
            IAgentAreaRecordService agentAreaRecordService,
            IRedPacketData redPacketData,
            IDatabaseContext databaseContext,
            IRedPacketReceiveData redPacketReceiveData,
            IWalletData walletData,
            IUserFlowRecordData userFlowRecordData,
            IWalletService walletService,
            IZoneService zoneService)
        {
            this.applicationContextService = applicationContextService;
            this.userAuthData = userAuthData;
            this.userData = userData;
            this.ipAddressRecordData = ipAddressRecordData;
            this.weChatUserInfoData = weChatUserInfoData;
            this.weChatUserRelevantService = weChatUserRelevantService;
            this.redisService = redisService;
            this.redisClearService = redisClearService;
            this.agentAreaRecordService = agentAreaRecordService;
            this.redPacketData = redPacketData;
            this.databaseContext = databaseContext;
            this.redPacketReceiveData = redPacketReceiveData;
            this.walletData = walletData;
            this.userFlowRecordData = userFlowRecordData;
            this.walletService = walletService;
            this.zoneService = zoneService;
        }

        public UserDto Create(UserRequestDto userRequestDto, string ip, RoleType roleType)
        {
            if (this.userData.CheckUserExistsByPhone(userRequestDto.Phone).GetAwaiter().GetResult())
            {
                throw new ArgumentException("此手机号已存在，无法重复注册");
            }

            UserEntity entity = userRequestDto.As<UserEntity>();
            entity.Role = roleType.ToString();
            entity.AccountStatus = AccountStatus.Using;

#if DEBUG
            entity.Password = userRequestDto.Password.SHA256(userRequestDto.Phone.TrimStart('0'));

#else
            string pwd = AESUtils.AESDecrypt(userRequestDto.Password);
            entity.Password = pwd.SHA256(userRequestDto.Phone.TrimStart('0'));
#endif
            entity.Password = userRequestDto.Password.SHA256(userRequestDto.Phone);
            entity.UniqueCode = string.Empty;
            IPAddressRecordEntity iPAddressRecordEntity = new IPAddressRecordDto() { StartIP = ip }.As<IPAddressRecordEntity>();
            IPAddressRecordEntity iPAddressRecordEntityResult = ipAddressRecordData.Get(iPAddressRecordEntity);
            entity.LogonIp = ip;
            entity.AddressIp = iPAddressRecordEntityResult != null ? iPAddressRecordEntityResult.IANA : "未知IP地址";
            var result = this.userData.Create(entity).GetAwaiter().GetResult().As<UserDto>();
            return result;
        }

        public UserDto GetUserByPhone(string phone)
        {
            return this.userData.GetUserByPhone(phone).As<UserDto>();
        }

        public UserDto GetUserByUserId(long userId)
        {
            UserEntity userEntity = this.redisService.TryGet(string.Format("{0}:UserId={1}", EntityNameConst.UserEntity, userId), () =>
            {
                return this.userData.GetUserByUserId(userId).GetAwaiter().GetResult();
            }, TimeSpan.FromMinutes(30));
            return userEntity.As<UserDto>();
        }

        public PageableList<WeChatUserInfoDto> GetUserList(string userName, string phone, string identityNumber, AccountStatus? accountStatus, RoleType? roleType, DateTime? start, DateTime? end, bool? ascending, int pageIndex = 1, int pageSize = 10)
        {
            var data = this.userData.GetUserList(userName, phone, identityNumber, accountStatus, roleType, start, end, ascending, pageIndex, pageSize).GetAwaiter().GetResult();
            return new PageableList<WeChatUserInfoDto>
            {
                Count = data.Item2,
                Items = data.Item1.Select(p => p.As<WeChatUserInfoDto>())
            };
        }

        public UserDto Logon(string phone, string password, string ip)
        {
            if (string.IsNullOrWhiteSpace(phone))
            {
                throw new ArgumentException("请输入手机号");
            }

            if (string.IsNullOrWhiteSpace(password))
            {
                throw new ArgumentException("请输入密码");
            }

            UserEntity entity = this.userData.GetUserByPhone(phone.TrimStart('0')).GetAwaiter().GetResult();

            if (entity == null)
            {
                throw new ArgumentException("手机号未注册，请先进行注册再登录");
            }

#if DEBUG
            if (password.SHA256(phone.TrimStart('0')) != entity.Password)
            {
                throw new ArgumentException("用户密码错误。");
            }
#else
            string pwd = AESUtils.AESDecrypt(password);
            if (pwd.SHA256(phone.TrimStart('0')) != entity.Password)
            {
                throw new ArgumentException("用户密码错误。");
            }
#endif

            try
            {
                // TODO: 以下查询 IP 地址的方法，当用户通过了代理，可能会出错，需要修改。
                IPAddressRecordEntity iPAddressRecordEntity = new IPAddressRecordDto() { StartIP = ip }.As<IPAddressRecordEntity>();
                IPAddressRecordEntity iPAddressRecordEntityResult = ipAddressRecordData.Get(iPAddressRecordEntity);
                entity.LogonIp = ip;
                entity.AddressIp = iPAddressRecordEntityResult != null ? iPAddressRecordEntityResult.IANA : "未知IP地址";
                this.userData.UpdateLoginInfo(entity.Phone, ip, entity.AddressIp);
            }
            catch { }

            if (entity.AccountStatus == AccountStatus.Deleted)
            {
                throw new ArgumentException("此账号已被删除!");
            }
            else if (entity.AccountStatus == AccountStatus.Stop)
            {
                throw new ArgumentException("此账号已被暂停使用，请联系员工!");
            }

            return entity.As<UserDto>();
        }

        public UserDto UpdateAvatar(string phone, string avatar)
        {
            UserEntity entity = this.userData.GetUserByPhone(phone).GetAwaiter().GetResult();
            if (entity == null)
            {
                throw new ArgumentException("当前用户不存在");
            }

            entity.Avatar = avatar;

            if (this.userData.UpdateAvatar(entity).GetAwaiter().GetResult())
            {
                this.redisClearService.ClearUser(entity.UserId);
            }
            return this.userData.GetUserByPhone(phone).Result.As<UserDto>();
        }

        public void UpdateLoginInfo(string phone, string ip)
        {
            IPAddressRecordEntity iPAddressRecordEntity = new IPAddressRecordDto() { StartIP = ip }.As<IPAddressRecordEntity>();
            IPAddressRecordEntity iPAddressRecordEntityResult = ipAddressRecordData.Get(iPAddressRecordEntity);
            string addressIp = iPAddressRecordEntityResult != null ? iPAddressRecordEntityResult.IANA : "未知IP地址";
            this.userData.UpdateLoginInfo(phone, ip, addressIp);
        }

        public bool UpdatePassword(string phone, string password)
        {
            UserEntity user = this.userData.GetUserByPhone(phone).GetAwaiter().GetResult();
            if (user == null)
            {
                throw new ArgumentException("当前用户不存在");
            }

#if DEBUG
            user.Password = password.SHA256(phone);
#else
            string pwd = AESUtils.AESDecrypt(password);
            user.Password = pwd.SHA256(phone.TrimStart('0'));
#endif


            bool result = this.userData.UpdatePassword(user).GetAwaiter().GetResult();
            if (result)
            {
                this.redisClearService.ClearUser(user.UserId);
            }
            return result;
        }

        public bool UserChangePassword(UserDto userDto, UserPutChangePasswordDto userPutChangePasswordDto)
        {

            if (userDto == null)
            {
                throw new ArgumentException("请重新登录");
            }
            UserEntity entity = this.userData.GetUserByUserId(userDto.UserId).GetAwaiter().GetResult();
            if (!userPutChangePasswordDto.NewPassword.Equals(userPutChangePasswordDto.ReNewPassword))
            {
                throw new ArgumentException("确认新密码与新密码不一致");
            }
            if (!entity.Password.Equals(userPutChangePasswordDto.Password.SHA256(userDto.Phone)))
            {
                throw new ArgumentException("原密码错误");
            }
            string newPassword = userPutChangePasswordDto.NewPassword.SHA256(userDto.Phone);
            if (entity.Password.Equals(newPassword))
            {
                throw new ArgumentException("新密码不能与原密码相同");
            }
            entity.Password = newPassword;
            bool result = this.userData.UpdatePassword(entity).GetAwaiter().GetResult();
            if (result)
            {
                this.redisClearService.ClearUser(entity.UserId);
            }
            return result;


        }

        public bool UpdatePhone(long userId, string phone, string password)
        {
            UserEntity entity = this.userData.GetUserByUserId(userId).GetAwaiter().GetResult();
            if (entity == null)
            {
                throw new ArgumentException("当前用户不存在");
            }
            if (entity.Password != password.SHA256(phone))
            {
                throw new ArgumentException("原密码错误");
            }
            entity.UserId = userId;
            entity.Phone = phone;

#if DEBUG
            entity.Password = password.SHA256(phone);
#else
            string pwd = AESUtils.AESDecrypt(password);
            entity.Password = pwd.SHA256(phone.TrimStart('0'));
#endif
            bool result = this.userData.UpdatePhone(entity).GetAwaiter().GetResult();
            if (result)
            {
                this.redisClearService.ClearUser(userId);
            }
            return result;
        }

        /// <summary>
        /// 验证码登录--废弃
        /// </summary>
        /// <param name="phone">手机号</param>
        /// <returns></returns>
        public UserDto PassCodeLogon(string phone)
        {
            UserEntity entity = this.userData.GetUserWithUnionIdByPhone(phone.TrimStart('0')).GetAwaiter().GetResult();
            if (entity == null)
            {
                //先注册
                UserEntity user = new UserEntity
                {
                    Avatar = "assets/centerimg.png",
                    Phone = phone,
                    Password = phone.Substring(phone.Length - 6, 6),
                    Role = RoleType.User.ToString(),
                    AccountStatus = AccountStatus.Using,
                    LogonIp = "0.0.0.0",
                    AddressIp = ""
                };
                return this.userData.Create(user).Result.As<UserDto>();
            }
            else
            {
                return entity.As<UserDto>();
            }
        }

        /// <summary>
        /// 微信授权用户(小程序专用)
        /// </summary>
        /// <param name="code">临时登录Code</param>
        /// <returns></returns>
        public UserDto WechatUserLogon(string code)
        {
            var weChatUserDto = this.weChatUserRelevantService.MinProgramLogin(code);
            if (weChatUserDto == null)
            {
                throw new ArgumentException("微信用户不存在");
            }
            var result = userAuthData.Get(weChatUserDto.Unionid).GetAwaiter().GetResult();
            if (result == null)
            {
                throw new ArgumentException("此用户并未绑定微信");
            }

            return this.GetUserByUserId(Convert.ToInt64(result.UserId));
        }

        /// <summary>
        /// 根据unionId获取微信用户信息
        /// </summary>
        /// <param name="unionId">unionId</param>
        /// <returns></returns>
        public WeChatUserInfoDto GetWechatUserByUnionId(string unionId)
        {
            return this.weChatUserInfoData.GetWechatUserByUnionId(unionId).As<WeChatUserInfoDto>();
        }

        /// <summary>
        /// 绑定微信账号
        /// </summary>
        /// <param name="user">当前登录用户</param>
        /// <param name="code">临时登录Code</param>
        /// <returns></returns>
        public WeChatUserInfoDto BindWechat(UserDto user, string code)
        {
            if (user == null)
            {
                throw new ArgumentException("当前用户不存在");
            }
            var weChatUserDto = this.weChatUserRelevantService.MinProgramLogin(code);
            if (weChatUserDto == null)
            {
                throw new ArgumentException("微信用户信息登录失败");
            }

            if (this.userAuthData.CheckUserAuthExists(user.UserId, AuthType.WeChat, weChatUserDto.Unionid).GetAwaiter().GetResult())
            {
                throw new ArgumentException("此用户已绑定微信用户信息");
            }
            UserAuthEntity userAuthEntity = this.userAuthData.Add(new UserAuthEntity()
            {
                AuthType = AuthType.WeChat,
                UnionId = weChatUserDto.Unionid,
                UserId = user.UserId,
                AuthInfo = ""
            }).GetAwaiter().GetResult();
            //weChatUserDto = this.weChatUserRelevantService.GetUserInfo(weChatUserDto.Openid);
            //this.weChatUserInfoData.Add(weChatUserDto.As<WeChatUserInfoEntity>());
            return this.weChatUserInfoData.Get(user.UserId.ToString(), weChatUserDto.Unionid).As<WeChatUserInfoDto>();
        }

        /// <summary>
        /// 解除绑定微信账号
        /// </summary>
        /// <param name="user">当前登录用户</param>
        /// <returns></returns>
        public void UnBindWechat(UserDto user)
        {
            if (user == null)
            {
                throw new ArgumentException("当前用户不存在");
            }
            var userAuthEntity = userAuthData.Get(user.UserId).GetAwaiter().GetResult();
            if (userAuthEntity == null)
            {
                throw new ArgumentException("用户已解绑微信账号");
            }
            this.userAuthData.Delete(userAuthEntity.UserAuthId);
        }

        /// <summary>
        /// 修改用户昵称
        /// </summary>
        /// <param name="userId">用户Id</param>
        /// <param name="nickName">用户昵称</param>
        /// <returns></returns>
        public UserDto UpdateNickName(long userId, string nickName)
        {
            UserEntity entity = this.userData.GetUserByUserId(userId).GetAwaiter().GetResult();
            if (entity == null)
            {
                throw new ArgumentException("当前用户不存在");
            }

            entity.UserName = nickName;

            return this.userData.UpdateUserName(userId, nickName, entity.IdentityCardNo).Result.As<UserDto>();
        }

        /// <summary>
        /// 修改用户信息
        /// </summary>
        /// <param name="userId">用户Id</param>
        /// <param name="userSimPutDto">用户Sim</param>
        /// <returns></returns>
        public UserDto UpdateUserInfo(long userId, UserSimPutDto userSimPutDto)
        {
            UserEntity userEntity = this.userData.GetUserByUserId(userId).GetAwaiter().GetResult();
            if (userEntity.Phone != userSimPutDto.Phone && this.userData.CheckUserExistsByPhone(userSimPutDto.Phone).GetAwaiter().GetResult())
            {
                throw new ArgumentException("此手机已存在，无法修改手机号");
            }
            UserEntity user = userSimPutDto.As<UserEntity>();
            user.UserId = userId;
            string password = userSimPutDto.Password.SHA256(userSimPutDto.Phone);
            if (userEntity.Password != password)
            {
                user.Password = password;
            }
            if (userEntity.IsVip != userSimPutDto.IsVip)
            {
                user.IsVip = userSimPutDto.IsVip;
            }
            if (userEntity.IsEnterprise != userSimPutDto.IsEnterprise)
            {
                user.IsEnterprise = userSimPutDto.IsEnterprise;
            }
            if (userEntity.ProvinceCode != userSimPutDto.ProvinceCode)
            {
                user.ProvinceCode = userSimPutDto.ProvinceCode;
            }
            if (userEntity.CityCode != userSimPutDto.CityCode)
            {
                user.CityCode = userSimPutDto.CityCode;
            }
            if (userEntity.CountyCode != userSimPutDto.CountyCode)
            {
                user.CountyCode = userSimPutDto.CountyCode;
            }
            var userEntityTask = this.userData.UpdateUserInfo(user);
            var entity = userEntityTask.GetAwaiter().GetResult();
            if (entity != null)
            {
                this.redisClearService.ClearUser(entity.UserId);
            }
            return entity.As<UserDto>();
        }

        public async Task<bool> CheckUser(long userId)
        {
            return await userData.CheckUserId(userId);
        }

        public bool ReceiveRedPacket(UserDto userInfo, long redPacketId, string countyCode)
        {
            if (string.IsNullOrWhiteSpace(countyCode))
            {
                throw new ArgumentException(" 省市区不可为空 ");
            }
            var zoneEntity = zoneService.GetFromZoneEntity(countyCode);
            if (zoneEntity == null || zoneEntity.provinceEntity == null || zoneEntity.cityEntity == null || zoneEntity.countyEntity == null)
            {
                throw new ArgumentException("此区域信息不正确!");
            }
            var agentAreaRecordEntity = agentAreaRecordService.GetLastLevelByCode(zoneEntity.countyEntity.CountyCode);
            if (agentAreaRecordEntity == null)
            {
                throw new ArgumentException(" 当前地区不在管辖内 ");
            }
            if (userInfo.IsReceiveRedPacket)
            {
                throw new ArgumentException(" 当前员工已领取过注册红包,不可重复领取 ");
            }
            var redPacket = this.redPacketData.GetSingle(redPacketId).Result;
            if (redPacket == null)
            {
                throw new ArgumentException(" 获取红包失败 ");
            }
            if (redPacket.AgentRecordId != agentAreaRecordEntity.AgentRecordId)
            {
                throw new ArgumentException(" 当前红包信息错误,不可领取 ");
            }
            int redPacketNumber = 1;
            var tempRedPacketNumber = redPacketReceiveData.GetRedPacketNumber().GetAwaiter().GetResult();
            if (tempRedPacketNumber != null)
            {
                redPacketNumber = tempRedPacketNumber.RedPacketNumber + 1;
            }
            var tempRedPacketReceiveEntity = this.redPacketReceiveData.GetEntityByRedPacketId(redPacket.RedPacketId, userInfo.UserId).Result;
            if (tempRedPacketReceiveEntity != null)
            {
                throw new ArgumentException(" 当前红包已被领取,不可重复领取 ");
            }
            var redPacketReceive = new RedPacketReceiveEntity()
            {
                RedPacketNumber = redPacketNumber,
                UserId = userInfo.UserId,
                UserName = userInfo.UserName,
                RedPacketId = redPacket.RedPacketId,
                RedPacketAmount = redPacket.RedPacketAmount,
                RedPacketTypeId = redPacket.RedPacketTypeId,
                RedPacketType = redPacket.RedPacketType,
                RedPacketName = redPacket.RedPacketName,
                GrundlagenType = GrundlagenTypeEnum.Register.ToString(),
                CreateTime = DateTime.Now,
                ProvinceCode = zoneEntity.provinceEntity.ProvinceCode,
                CityCode = zoneEntity.cityEntity.CityCode,
                CountyCode = zoneEntity.countyEntity.CountyCode,
                AgentRecordId = agentAreaRecordEntity.AgentRecordId,
            };
            this.databaseContext.BeginTransaction();
            redPacketReceiveData.InsertAsync(redPacketReceive).GetAwaiter().GetResult();
            var redPacketEntity = this.redPacketData.Receive(redPacketId).GetAwaiter().GetResult();
            if (redPacketEntity.RemainCount < 0)
            {
                throw new ArgumentException(" 当前红包已被领完,不可领取 ");
            }
            this.userData.ReceiveRedPacket(userInfo.UserId).GetAwaiter().GetResult();
            var walletDto = this.walletService.GetWalletByUserId(userInfo.UserId);
            walletDto.Balance += redPacket.RedPacketAmount;
            walletDto = this.walletService.Update(walletDto);
            var userFlowRecord = new UserFlowRecordEntity()
            {
                FlowType = FlowType.Other,
                Balance = walletDto.Balance,
                FlowDirection = SourceFlowDirectionType.Income,
                Amount = redPacket.RedPacketAmount,
                UserId = userInfo.UserId,
                UserName = userInfo.UserName,
                Channel = PaymentChannelType.System,
                Remark = "注册红包,免费领取",
                CreateTime = DateTime.Now,
                RiskLevel = SourceRiskLevelType.Normal,
            };
            userFlowRecordData.AddAsync(userFlowRecord).GetAwaiter().GetResult();
            this.databaseContext.Commit();
            this.redisClearService.ClearUser(userInfo.UserId);
            return true;
        }

        public RedPacketDto GetRemainRedPacket(string countyCode)
        {
            var zoneEntity = zoneService.GetFromZoneEntity(countyCode);
            if (zoneEntity == null || zoneEntity.provinceEntity == null || zoneEntity.cityEntity == null || zoneEntity.countyEntity == null)
            {
                throw new ArgumentException("此区域信息不正确!");
            }
            var agentAreaRecordEntity = agentAreaRecordService.GetLastLevelByCode(zoneEntity.countyEntity.CountyCode);
            if (agentAreaRecordEntity == null)
            {
                throw new ArgumentException(" 当前地区不在管辖范围内 ");
            }
            var redPacketRemainList = redPacketData.GetRemainList(true, agentAreaRecordEntity.AgentRecordId, GrundlagenTypeEnum.Register).Result;
            RedPacketDto redPacketDto = null;
            if (redPacketRemainList.Any())
            {
                redPacketDto = redPacketRemainList.OrderByDescending(P => P.RedPacketAmount).FirstOrDefault().As<RedPacketDto>();
            }
            return redPacketDto;
        }


        #region 实名认证

        public UserDto RealNameVerifies(UserDto userInfo, UserRealNameVerifiesRequestDto verifiesRequestDto)
        {
            if (this.userData.GetUserByUserId(userInfo.UserId).GetAwaiter().GetResult() == null)
            {
                throw new ArgumentException("用户信息不存在。");
            }
            //校验省市区
            var zoneEntity = zoneService.GetFromZoneEntity(verifiesRequestDto.CountyCode);
            if (zoneEntity == null || zoneEntity.provinceEntity == null || zoneEntity.cityEntity == null || zoneEntity.countyEntity == null)
            {
                throw new ArgumentException("此区域信息不正确!");
            }
            var user = new UserEntity()
            {
                UserId = userInfo.UserId,
                RealName = verifiesRequestDto.RealName,
                IdentityCardNo = verifiesRequestDto.IdentityCardNo,
                IdentityCardPath = verifiesRequestDto.IdentityCardPath,
                IdentityCardBackPath = verifiesRequestDto.IdentityCardBackPath,
                RealNameVerifiesStatus = RealNameVerifiesStatus.Pending.ToString(),
                ProvinceId = zoneEntity.provinceEntity.ProvinceId,
                ProvinceCode = zoneEntity.provinceEntity.ProvinceCode,
                ProvinceName = zoneEntity.provinceEntity.ProvinceName,
                CityId = zoneEntity.cityEntity.CityId,
                CityCode = zoneEntity.cityEntity.CityCode,
                CityName = zoneEntity.cityEntity.CityName,
                CountyId = zoneEntity.countyEntity.CountyId,
                CountyCode = zoneEntity.countyEntity.CountyCode,
                CountyName = zoneEntity.countyEntity.CountyName
            };
            var result = this.userData.RealNameVerifiesAsync(user).GetAwaiter().GetResult();
            if (result == null)
            {
                throw new ArgumentException("实名认证失败。");
            }
            string cacheKey = string.Format("{0}:UserId={1}", EntityNameConst.UserEntity, userInfo.UserId);
            this.redisService.DeleteMultipleKey(cacheKey, false);
            return result.As<UserDto>();
        }

        public UserDto RealNameVerifiesApprove(AdminDto admin, long userId, UserApproveRequestDto dto)
        {

            if (this.userData.GetUserByUserId(userId).GetAwaiter().GetResult() == null)
            {
                throw new ArgumentException("用户信息不存在。");
            }
            if (!dto.IsApproved)
            {
                if (string.IsNullOrWhiteSpace(dto.RefuseToReason))
                {
                    throw new ArgumentException("审核不通过,请填写原因。");
                }
            }
            var user = new UserEntity()
            {
                UserId = userId,
                RealNameVerifiesRefuse = dto.RefuseToReason,
                RealNameVerifiesStatus = dto.IsApproved ? RealNameVerifiesStatus.Success.ToString() : RealNameVerifiesStatus.Refused.ToString(),
                Approver = admin.FullName,
                ApproverId = admin.AdminId,
                ApproveTime = DateTime.Now
            };
            var result = this.userData.RealNameVerifiesApproveAsync(user).GetAwaiter().GetResult();
            if (result == null)
            {
                throw new ArgumentException("实名认证审核失败。");
            }            
            string cacheKey = string.Format("{0}:UserId={1}", EntityNameConst.UserEntity, userId);
            this.redisService.DeleteMultipleKey(cacheKey, false);
            return result.As<UserDto>();
        }

        #endregion
    }
}
